//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

package admin_user_resume_api_serv

import (
	"context"

	"atomgit.com/openlinksaas/api-server/admin_api_serv/admin_common"
	"atomgit.com/openlinksaas/api-server/config"
	"atomgit.com/openlinksaas/api-server/dao"
	"atomgit.com/openlinksaas/api-server/dao/user_dao"
	"atomgit.com/openlinksaas/proto-gen-go.git/user_resume_api"
)

type UserResumeAdminApiImpl struct {
	user_resume_api.UnimplementedUserResumeAdminApiServer
	adminCfg *config.AdminCfg
}

func NewUserResumeAdminApiImpl(adminCfg *config.AdminCfg) *UserResumeAdminApiImpl {
	return &UserResumeAdminApiImpl{adminCfg: adminCfg}
}

func (apiImpl *UserResumeAdminApiImpl) Get(ctx context.Context, req *user_resume_api.AdminGetRequest) (*user_resume_api.AdminGetResponse, error) {
	emptyInfo := &user_resume_api.UserResumeInfo{
		BasicInfo:       &user_resume_api.BasicInfo{},
		WorkExpItemList: []*user_resume_api.WorkExpItem{},
		EduExpItemList:  []*user_resume_api.EduExpItem{},
	}

	sess, ok := dao.CacheDao.GetAdminSession(ctx, req.AdminSessionId)
	if !ok {
		return &user_resume_api.AdminGetResponse{
			Code:       user_resume_api.AdminGetResponse_CODE_WRONG_SESSION,
			ErrMsg:     "会话不存在",
			ResumeInfo: emptyInfo,
		}, nil
	}
	if !sess.AuthOk {
		return &user_resume_api.AdminGetResponse{
			Code:       user_resume_api.AdminGetResponse_CODE_NOT_AUTH,
			ErrMsg:     "未授权会话",
			ResumeInfo: emptyInfo,
		}, nil
	}
	adminUserCfg, err := admin_common.GetAdminUserConfig(ctx, apiImpl.adminCfg, sess.UserName)
	if err != nil {
		return nil, err
	}
	if !adminUserCfg.PermInfo.UserPerm.Read {
		return &user_resume_api.AdminGetResponse{
			Code:       user_resume_api.AdminGetResponse_CODE_NO_PERMISSION,
			ErrMsg:     "没有权限",
			ResumeInfo: emptyInfo,
		}, nil
	}

	resumeItem, err := user_dao.UserResumeDao.Get(ctx, req.TargetUserId)
	if err != nil {
		return &user_resume_api.AdminGetResponse{
			Code:       user_resume_api.AdminGetResponse_CODE_OK,
			ResumeInfo: emptyInfo,
		}, nil
	}
	accessItem, err := user_dao.ResumeAccessDao.Get(ctx, req.TargetUserId)
	if err != nil {
		return &user_resume_api.AdminGetResponse{
			Code:       user_resume_api.AdminGetResponse_CODE_OK,
			ResumeInfo: emptyInfo,
		}, nil
	}

	return &user_resume_api.AdminGetResponse{
		Code:       user_resume_api.AdminGetResponse_CODE_OK,
		ResumeInfo: resumeItem.ToUserResumeInfo(accessItem),
	}, nil
}
